/**
Implements the str_cli_ext function.
*/
#include "globals.h"

/**
The string interface function for the client. It reads input from a file
descriptor, writes the data to the socket (connected to the server), reads back 
the data from the socket and writes the data read to stdout.

@param fp supplies the file descriptor.
@aparam sockfd supplies the socket file descriptor.
@param pfd supplies the pipe file descriptor.
*/
void 
str_cli_ext(
    FILE* fp,
    int sockfd,
    int pfd
    )
{
    int maxfd;
    int stdineof;
    fd_set rset;
    char buf[MAXLINE];
    int n;

    //
    // Indicates if EOF has been pressed.
    //

    stdineof = 0;

    FD_ZERO(&rset);

    while (TRUE)
    {
        if (stdineof == 0)
        {
            FD_SET(fileno(fp), &rset);
        }

        //
        // Initialize descriptors for select function. We are interested in both
        // the input file descriptor and the socket descriptor.
        //

        FD_SET(sockfd, &rset);
        maxfd = max(fileno(fp), sockfd) + 1;
        Select(maxfd, &rset, NULL, NULL, NULL);

        if (FD_ISSET(sockfd, &rset))
        {
            if ((n = Readline(sockfd, buf, MAXLINE)) == 0)
            {
                //
                // No more data to be read. 
                //

                if (stdineof == 1)
                {
                    //
                    // The socket has already been issued the shut down command.
                    // No more cleanup required.
                    //

                    return;
                }
                else
                {
                    //
                    // Server has crashed. CLeanup and exit.
                    //

                    Write(pfd, SRV_PREMATURE_TERM, strlen(SRV_PREMATURE_TERM));
                    Close(pfd);
                    err_quit("str_cli: server terminated prematurely");
                }
            }
            
            Write(fileno(stdout), buf, n);
       }

        if (FD_ISSET(fileno(fp), &rset))
        {
            //
            // No more data to be read from input file. Set eof flag and shut
            // down.
            //

            if ((n = Readline(fileno(fp), buf, MAXLINE)) == 0)
            {
                stdineof = 1;
                Shutdown(sockfd, SHUT_WR);
                FD_CLR(fileno(fp), &rset);
                continue;
            }
            
            Write(sockfd, buf, n);
        }
    }
}

